#include "GUIElement.h"

GUIElement::GUIElement()
{
    state = Normal;
    padding = 4;
    width = 16; // temp setting
    height = 16; // temp setting
    text = "";
    fontSize = 16;
    borderSize = 1;
    isPressed = isHovered = false;

    // Default colors
    bgColor[Normal] = &White;
    bgColor[Hover] = new Color(0.7f, 0.7f, 0.7f, 1.0f);
    bgColor[Active] = new Color(0.7f, 0.7f, 0.7f, 1.0f);
    borderColor[Normal] = &Gray;
    borderColor[Hover] = &Gray;
    borderColor[Active] = &Black;
    textColor[Normal] = &Gray;
    textColor[Hover] = &Gray;
    textColor[Active] = &Black;
}

void GUIElement::handleEvents(SDL_Event* event)
{
    if(event->type == SDL_MOUSEBUTTONDOWN)
    {
        // We only care if the mouse is already over this element
        if (isHovered)
        {
            int mx,my;
            Uint8 mState = SDL_GetMouseState(&mx,&my);
            onPressed(mState);
            state = Active;
            isPressed = true;
        }
    }
    else if(event->type == SDL_MOUSEBUTTONUP)
    {
        // We only care if the mouse is already over this element
        if (isHovered)
        {
            int mx,my;
            Uint8 mState = SDL_GetMouseState(&mx,&my);
            onReleased(mState);
            state = Hover;
            isPressed = false;
        }
    }
    else if (event->type == SDL_MOUSEMOTION)
    {
        // Check if mouse position is contained within the element's hitbox.
        if ((float)event->motion.x >= getGlobalX() && (float)event->motion.x <= (getGlobalX()+width) &&
            (float)event->motion.y >= getGlobalY() && (float)event->motion.y <= (getGlobalY()+height))
        {
            if (isPressed)
                state = Active;
            else
                state = Hover;
            isHovered = true; // Signal that the button is being hovered.
        }
        else
        {
            state = Normal;
            isHovered = false;
            isPressed = false;
        }
    }
}

void GUIElement::setState(ElementState elemState)
{
    state = elemState;
    if (state == Active)
    {
        isPressed = true;
        isHovered = false;
    }
    else if (state == Hover)
    {
        isPressed = false;
        isHovered = true;
    }
    else
    {
        isPressed = false;
        isHovered = false;
    }
}
